package com.chapter_5;

/**
 * @Author: Timo
 * @Date: 2019/5/15 14:49
 * @Description: 桌子
 */
public class Table {
    /**
     * 蛋糕实际放置位置。
     */
    private final String[] buffer;
    /**
     * 下次put的位置
     */
    private int tail;
    /**
     * 下次take的位置
     */
    private int head;
    /**
     * buffer中的蛋糕个数
     */
    private int count;


    public Table(int count) {
        this.buffer = new String[count];
        this.head = 0;
        this.tail = 0;
        this.count = 0;
    }


    /**
     * 放置蛋糕
     *
     * @param cake
     */
    public synchronized void put(String cake) throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + " puts " + cake + " count: "+count + " length:"+buffer.length);
        //如果当前蛋糕大于桌子可摆放蛋糕数量的时候，需要等待客人将蛋糕拿走之后才能摆放
        while (count >= buffer.length) {
            System.out.println(Thread.currentThread().getName() + " wait BEGIN....");
            wait();
            System.out.println(Thread.currentThread().getName() + " wait END");
        }
        buffer[tail] = cake;
        tail = (tail + 1) % buffer.length;
        count++;
        notifyAll();
    }

    public synchronized String take() throws InterruptedException {
        // 判断当前是否有蛋糕可以取，如果没有的话就继续等待
        while (count < 0) {
            System.out.println(Thread.currentThread().getName() + " wait BEGIN");
            wait();
            System.out.println(Thread.currentThread().getName() + " wait END");
        }

        // 取出第一个蛋糕
        String cake = buffer[head];
        head = (head + 1) % buffer.length;
        count--;
        notifyAll();
        System.out.println(Thread.currentThread().getName() + " take " + cake);
        return cake;
    }
}
